package queue;


public class AchieveQueueOfArray {

    public int[] queArray;
    public static int length;//数组中元素的个数
    public int maxsize;
    public int rear;//队尾元素的下标
    public int front;//队首元素的下标

    //通过构造方法实现对队列的初始化
    public AchieveQueueOfArray(int maxsize) {
        this.maxsize = maxsize;
        queArray = new int[maxsize];
        length = 0;
        rear = -1;
        front = 0;
    }

    //入队
    public int insert(int item) {
        if (isFull()) {
            doubleArray();
        }
        queArray[++rear] = item;
        length++;
        return item;
    }

    //扩容
    public void doubleArray() {
        int[] newArray = new int[maxsize * 2];
        for (int i = 0; i < maxsize; i++) {
            newArray[i] = queArray[i];
        }
        maxsize = maxsize * 2;
        queArray = newArray;
    }

    //出队
    public int outQueue() throws Exception {
        if (isEmpty()) {
            throw new Exception("队列为空，不能执行删除操作");
        }
        if (front == maxsize) {
            front = 0;
        }
        length--;
        return queArray[front++];
    }

    //判空
    public boolean isEmpty() {
        return (length == 0);
    }

    //判满
    public boolean isFull() {
        return (length == maxsize);
    }

    //查看队头元素
    public int seek() throws Exception {
        if (isEmpty()) {
            throw new Exception("队列为空，不能查看队头元素");
        }
        return queArray[front];
    }

    //显示队列的元素
    public void showQueue() {
        if (isEmpty()){
            throw new RuntimeException("队列空。。。");
        }
        for (int i = front; i <= rear; i++) {
            System.out.printf("queue[%d]=%d\n",i,queArray[i]);
        }
    }

    public static void main(String[] args) throws Exception {
        AchieveQueueOfArray que = new AchieveQueueOfArray(3);
        que.insert(1);
        que.insert(2);
        que.insert(4);

        System.out.println("头元素-------" + que.seek());
        System.out.println("是否为空" + que.isEmpty());
        System.out.println("是否满了" + que.isFull());
        que.showQueue();
        System.out.println("--------------------------------------------");

        int a = que.outQueue();
        que.showQueue();
        System.out.println("头元素" + que.seek());
        System.out.println("是否为空" + que.isEmpty());
        System.out.println("是否满了" + que.isFull());
        System.out.println("--------------------------------------------");

        que.outQueue();
        que.showQueue();
        System.out.println("头元素" + que.seek());
        System.out.println("是否为空" + que.isEmpty());
        System.out.println("是否满了" + que.isFull());
        System.out.println("--------------------------------------------");

        que.outQueue();
//        System.out.println("头元素" + que.seek());
        System.out.println("是否为空" + que.isEmpty());
        System.out.println("--------------------------------------------");

    }

}
